<?php
namespace app\admin\controller;
use app\model\Bill as BillModel;
use app\model\Admin as AdminModel;
use app\model\UserBill as UserBillModel;
use think\Db;


class Bill extends Base
{
    
    public $exception = ['explodebalance','qianyi','qianyi_d'];

    public function __construct(){
        $model = new BillModel();
        $this->model = $model;
        parent::__construct();
        
        $page_info = $this->page_info;
        $page_info['title'] = '账单';

        if ( in_array($page_info['action'], ['add','edit']) ) {
           
        }

        $model_dates = config('config.bill_dates');
        $this->assign([
            'model'=>$this->model,
            'page_info'=>$page_info,
            'model_dates'=>$model_dates
        ]);
    }

    public function getMap(){
        $map_params = [
            ['key'=>'ower_id','type'=>'='],
            ['key'=>'admin_id','type'=>'='],
            ['key'=>'order_id','type'=>'='],
            ['key'=>'related_order_id','type'=>'='],
            ['key'=>'product_code','type'=>'='],
            ['key'=>'subscription_type','type'=>'='],
            ['key'=>'order_type','type'=>'='],
            // ['key'=>'billing_cycle','type'=>'='],
        ];
        $map = getSearchParam($map_params);
        // if (isSearchParam('start_time') && isSearchParam('end_time')) {
        //     $map[] = ['create_time','between',[strtotime(input('start_time')),strtotime(input('end_time'))]];
        // }else if (isSearchParam('start_time')) {
        //     $map[] = ['create_time','>=',strtotime(input('start_time'))];
        // }else if (isSearchParam('end_time')) {
        //     $map[] = ['create_time','<=',strtotime(input('end_time'))];
        // }
        if (isSearchParam('start_time')) {
            $map[] = ['payment_time','>=',strtotime(input('start_time'))];
        }
        if (isSearchParam('end_time')) {
            $map[] = ['payment_time','<',strtotime(input('end_time'))];
        }
        if (input('is_new',0) == 1) {
            $ower_ids = Db::name('user')->where([
                Db::raw('pk is not null')
            ])->column('pk');
            $map[] = ['ower_id','in',$ower_ids];
        }
        if (isSearchParam('billing_cycle')) {
            $map[] = ['billing_cycle','like',input('billing_cycle').'%'];
        }
        return $map;
    }

    public function createSearch(){
        $model = $this->model;
        // $users = Db::name('user')->where(Db::raw('pk is not null'))->field('id,pk,name')->select();
        // $users  = arrayParamExtract($users ,'pk','name');
        $tmp_users = Db::name('user')->where(Db::raw('pk is not null'))->field('id,pk,name,mobile')->select();
        $users = [];
        foreach ($tmp_users as $k => $vo) {
            $users[$vo['pk']] = $vo['name'].'('.$vo['pk'].')';
        }

        $admins = AdminModel::select();
        $admins = arrayParamExtract($admins,'id','truename');

        $tmp_products = Db::name('product')->field('code,name')->select();
        $products = [];
        foreach ($tmp_products as $k => $vo) {
            $products[$vo['code']] = $vo['name'].'（'.$vo['code'].'）';
        }
        $search_params = [
            [
                ['key'=>'ower_id','name'=>'顾客','type'=>'select2_1','params'=>$users],
                ['key'=>'order_id','name'=>'订单号','type'=>'text'],
                ['key'=>'related_order_id','name'=>'主账号订单号','type'=>'text'],
                ['key'=>'admin_id','name'=>'所属管理员','type'=>'select2_1','params'=>$admins]
            ],[
                ['key'=>'start_time','name'=>'开始时间','type'=>'datetime'],
                ['key'=>'end_time','name'=>'结束时间','type'=>'datetime'],
                ['key'=>'order_type','name'=>'订单类型','type'=>'select1_1','params'=>BillModel::getOTypeList()],
                ['key'=>'subscription_type','name'=>'订阅类型','type'=>'select1_1','params'=>BillModel::getSubscriptionTypeList()],
            ],[
                ['key'=>'product_code','name'=>'产品','type'=>'select2_1','params'=>$products],
                // ['key'=>'is_new','name'=>'是否新平台','type'=>'select1_1','params'=>[1=>'是']],
                ['key'=>'page_size','name'=>'行数','type'=>'text','placeholder'=>'默认20，建议100内'],
                ['key'=>'billing_cycle','name'=>'账期','type'=>'text'],
            ]
        ];
        $this->assign([
            'search_params'=>$search_params
        ]);
    }

    public function index(){
        $model_date = session('bill_model_date');
        if (empty($model_date)) {
            $model = $this->model;
        }else{
            $model = Db::name('bill'.$model_date);
        }
        // 获取筛选条件
        $map = $this->getMap();
        // 创建搜索
        $this->createSearch();

        $page_param = [
            'page'=>input('page',1),
            'list_rows'=>emptyDef(input('page_size'),20)
        ];
        $list = $model->field('product_code,product_type,currency,goods_code,goods_name',true)->where($map)->order('id','desc')->paginate($page_param);
        $page = $list->render();

        $list = $list->toarray();
        $customers = [];
        $admins = [];
        foreach ($list['data'] as $k => $vo) {
            if (empty($customers[$vo['ower_id']])) {
                $customer = Db::name('user')->field('id,name,admin_id')->where('pk',$vo['ower_id'])->find();
                // $customer['admin_name'] = Db::name('admin')->where('id',$customer['admin_id'])->value('truename');
                $customers[$vo['ower_id']] = $customer;
            }
            if (empty($admins[$vo['ower_id']])) {
                $admins[$vo['ower_id']] = Db::name('admin')->where('id',$vo['admin_id'])->value('truename');
            }
         
            $list['data'][$k]['customer'] = $customers[$vo['ower_id']];
            $list['data'][$k]['admin_name'] = $admins[$vo['ower_id']];
        }
        return view('index', [
            'list'=>$list,
            'page'=>$page,
        ]);
    }

    public function exportTask(){
        // 获取筛选条件
        $map = $this->getMap();
        
        $save_data = [
            'params'=>json_encode($map),
            'task_sn'=>uuidCreate(),
            'ctime'=>time(),
            'type'=>2,
            'target_id'=>$this->login_user['id'],
            'name'=>'账单导出'.date('Ymd')
        ];

        $model_date = session('bill_model_date');
        if (empty($model_date)) {
            $save_data['table_name'] = 'bill';
        }else{
            $save_data['table_name'] = 'bill'.$model_date;
        }
        if ( Db::name('export_task')->insert($save_data) ) {
            $this->success('任务创建成功',url('export_task/index'));
        }else{
            $this->error('任务创建失败');
        }
    }

    public function exportIndex(){
        set_time_limit ( 0 );
        ini_set('memory_limit','20480M');

        // 获取筛选条件
        $map = $this->getMap();
        // 创建搜索
        $this->createSearch();

        $model_date = session('bill_model_date');
        if (empty($model_date)) {
            $model = $this->model;
        }else{
            $model = Db::name('bill'.$model_date);
        }

        $total = $model->where($map)->count();
        // $rows = floor($total * 0.2);
        // if ($rows > 1000000) {
        //     $rows = 1000000;
        // }else{
        //     $rows = 500000;
        // }
        $rows = 500000;
        return view('exportIndex', [
            'total'=>$total,
            'rows'=>$rows,
            'nums'=>ceil($total/$rows)
        ]);
    }

    public function export(){
        // echo(date('Y-m-d H:i:s'));
        set_time_limit ( 0 );
        ini_set('memory_limit','40960M');

        // 获取筛选条件
        $map = $this->getMap();

        $num = input('num',0);
        $rows = 500000;

        $model = $this->model;
        $model_date = session('bill_model_date');
        if (empty($model_date)) {
            $model2 = $this->model;
        }else{
            $model2 = Db::name('bill'.$model_date);
        }
        $no_fields = 'product_code,product_type,currency,goods_code,goods_name';
        if ($num > 0) {
            $list = $model2->field($no_fields,true)->limit(($num-1)*$rows,$rows)->where($map)->order('id','asc')->select(); 
        }else{
            $list = $model2->field($no_fields,true)->where($map)->order('id','asc')->select();   
        }
        
        $data = [];
        // $title = ['客户名称','订单号','主账号订单号','客户经理','产品名称','产品类型','订单类型','交易时间','服务开始时间','服务结束时间','创建时间','实例id','实例昵称','实例Tag','资源组','打包售卖ID','打包售卖信息','地域','实例配置','实例规格','公网ip','私网ip','可用区','计费项','服务时长','原价','平台成本','客户主管成本','客户经理成本','客户融合云实付','客户阿里云实付'];
        $title = ['客户名称','客户UID','客户手机','订单号','主账号订单号','客户经理','产品名称','订阅类型','订单类型','交易时间','服务开始时间','服务结束时间','创建时间','实例id','实例昵称','实例Tag','资源组','打包售卖ID','打包售卖信息','地域','实例配置','实例规格','公网ip','私网ip','可用区','计费项','服务时长','原价','平台成本','用户折扣','实付金额'];

        $tmp_users = Db::name('user')->where(Db::raw('pk is not null'))->field('id,pk,name,mobile')->select();
        $users  = arrayParamExtract($tmp_users ,'pk','name');
        $mobiles  = arrayParamExtract($tmp_users ,'pk','mobile');

        $admins = Db::name('admin')->field('id,truename')->select();
        $admins = arrayParamExtract($admins,'id','truename');

        $order_type_sn = $model->getOTypeList();
        foreach ($list as $k => $vo) {
            $tmp = [
                // $customers[$vo['ower_id']]['name'],
                $users[$vo['ower_id']],
                $vo['ower_id']."\t",
                $mobiles[$vo['ower_id']]."\t",
                $vo['order_id']."\t",
                $vo['related_order_id']."\t",
                // $admins[$vo['ower_id']],
                $admins[$vo['admin_id']],
                $vo['product_name'],
                // $vo['product_type'],
                $vo['subscription_type']=='Subscription'?'预付':'后付',
                $order_type_sn[$vo['order_type']],
                timeDef($vo['payment_time'],'','Y-m-d H:i:s'),
                $vo['usage_start_time'],
                $vo['usage_end_time'],
                timeDef($vo['create_time']),
                $vo['instance_id'],
                $vo['instance_nick'],
                $vo['tag'],
                $vo['resource_group'],
                $vo['solution_id'],
                $vo['solution_name'],
                $vo['region'],
                $vo['instance_config'],
                $vo['instance_spec'],
                $vo['public_ip'],
                $vo['private_ip'],
                $vo['zone'],
                $vo['fee_item'],
                $vo['service_duration'],
                $vo['pretax_gross_amount'],
                $vo['pretax_amount'],
                $vo['user_discount'],
                $vo['platform_amount']
                // $vo['trade_original_money'],
                // $vo['trade_mreal_money'],
                // $vo['admin_money'],
                // $vo['user_money'],
                // $vo['customer_money'],
                // $vo['trade_real_money']
            ];
            $data[] = $tmp;
        }
        // dump(count($data));die;
        exportCsv(date('YmdHis'),$title,$data);
        // $file_name = $num . ".csv";
        // $file_path= "C:/csv/"  . $file_name;

        // $data = implode("\r\n", $data);
        // file_put_contents($file_path, $data);
        // echo(date('Y-m-d H:i:s'));
    }

    public function selDates(){
        $model_dates = config('config.bill_dates');
        return view('selDates', [
            'list'=>$model_dates
        ]);
    }

    public function selDate($key='',$page='index'){
        if (empty($key)) {
            $key = null;
        }
        session('bill_model_date',$key);
        return redirect(url($page));
    }

   
}
